package com.example.communist_app_api.config.xss;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author love~mlm
 * @version 1.0
 * Create by 2022/9/27 20:30
 */

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    //子类不定义构造器的话，就没有办法接收请求对象，所以得声明构造器对象
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getParameter(String name) {
        //从请求中获取的原始数据
        String value= super.getParameter(name);
        if(!StrUtil.hasEmpty(value)){
            //转义一下赋值给value
            value= HtmlUtil.filter(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {

        String[] values= super.getParameterValues(name);
        if (values != null) {
            //遍历数组
            for (int i = 0; i < values.length; i++) {
                String value =values[i];
                if(!StrUtil.hasEmpty(value)){
                    value=HtmlUtil.filter(value);
                }
                values[i] = value;
            }
        }
        return values;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String,String[]> parameters =  super.getParameterMap();
        //定义一个保持原来队形的hashmap
        LinkedHashMap <String,String[]> map = new LinkedHashMap<>();
        if (parameters != null) {
            for (String key :parameters.keySet()) {
                String[] values = parameters.get(key);
                for (int i = 0; i < values.length; i++) {
                    String value =values[i];
                    if(!StrUtil.hasEmpty(value)){
                        value=HtmlUtil.filter(value);
                    }
                    values[i] = value;
                }
                map.put(key,values);
            }
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        String value =  super.getHeader(name);
        if (!StrUtil.hasEmpty(value)){
            value=HtmlUtil.filter(value);
        }
        return value;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        //返回是一个io流，所以还是得构建一个io流并且返回
        InputStream in= super.getInputStream();
        //创建一个字符流，从里面读数据
        InputStreamReader reader=new InputStreamReader(in, Charset.forName("UTF-8"));
        //为了读取数据的高效性，配一个缓存流
        BufferedReader buffer = new BufferedReader(reader);
        //从缓冲流读取的数据要保存起来，使用StringBuffer来做字符串拼接
        StringBuffer body = new StringBuffer();
        //读取行数据
        String line = buffer.readLine();
        //判断行数据是否有效
        while(line !=null){
            body.append(line);
            line = buffer.readLine();//读取下一行数据
            //如果为空就结束循环
        }
        //关闭流
        buffer.close();
        reader.close();
        in.close();
        //json格式转map格式
        Map<String,Object> map = JSONUtil.parseObj(body.toString());
        Map<String,Object> result = new LinkedHashMap<>();
        for (String key : map.keySet()) {
            Object val=map.get(key);
            //判断一下val是不是字符串格式的
            //如果不是就要转字符串
            if(val instanceof String){
                //判断是否为空
                if (!StrUtil.hasEmpty(val.toString())){
                    result.put(key,HtmlUtil.filter(val.toString()));
                }
            }else
                {//如果是字符串直接加入map中
                result.put(key,val);
                }
        }
        //map转json格式
        String json = JSONUtil.toJsonStr(result);
        //创建一个io流进行读数据
        ByteArrayInputStream bain = new ByteArrayInputStream(json.getBytes());
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bain.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }
}
